package com.example.bysj.Dao;
//201902104061徐中堂
import com.example.bysj.domain.authority.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
//声明数据库访问类
@Repository("resourceDao")
public class ResourceDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //根据id查询权限
    public Resource getResourceById(int id){
        String sql = "SELECT * FROM resource WHERE id=?";
        List<Resource> resources = jdbcTemplate.query(sql, new Object[]{id}, new RowMapper<Resource>() {
            @Override
            public Resource mapRow(ResultSet rs, int rowNum) throws SQLException {
                return new Resource(
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getString("resourceType"),
                        rs.getString("uri"),
                        rs.getString("permission"),
                        rs.getInt("parentId"),
                        rs.getInt("parentIds"),
                        rs.getInt("avaliable")
                );
            }
        });
        if (!resources.isEmpty()){
            return resources.get(0);
        } else {
            return null;
        }
    }

    //增加
    public boolean add(Resource resource) {
        String sql = "INSERT INTO resource (name,uri,resourceType,permission" +
                ",parentId,parentIds,avaliable) VALUES (?,?,?,?,?,?,?)";
        int affectedRowNum = jdbcTemplate.update(sql, resource.getName(),
                resource.getUri(),resource.getResourceType(),resource.getPermission()
                ,resource.getParentId(),resource.getParentIds(),resource.getAvaliable());
        if (affectedRowNum != 1) {
            return false;
        } else {
            return true;
        }
    }
}
